package com.chixing.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 封装了获得数据库的连接对象和关闭数据库
 * 从安全性、耦合性 需要单独封装数据库的连接与关闭操作
 */
public class DBConnection {
    public static Connection connection=null;
    public static Connection getConnection(){
        try {
            Class.forName(DataSourceFileUtil.getDriverName());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
             connection= DriverManager.getConnection(DataSourceFileUtil.getDriverURL(),
                    DataSourceFileUtil.getDriverUsername(),
                    DataSourceFileUtil.getPassword());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    public static void closeConnection(){
       if (connection!=null) {
           try {
               connection.close();
           } catch (SQLException e) {
               throw new RuntimeException(e);
           }
       }
    }
}
